
// JSON fix
Request.JSON2 = new Class({

	Extends: Request,

	options: {
		secure: true
	},


        send: function(json) {
            var jstring = JSON.encode( json );
            this.parent({data: {json: jstring}});
        },

	initialize: function(options){
		this.parent(options);
		this.headers.extend({'Accept': 'application/json', 'X-Request': 'JSON'});
	},

	success: function(text){
		this.response.json = JSON.decode(text, this.options.secure);
		this.onSuccess(this.response.json, text);
	}

});


// handle requests, request queues etc...
function Para_Requester( url, response_handler, error_handler ) {
    this.url              = url;
    this.requester = null;

    // attributes /// 
    this.pending_requests = new Array();
    this.current_request  = null;

    // methods /// ////////////////////////////////////////
    this.send        = Para_Requester_Send;
    this.send_next   = Para_Requester_SendNext;

}


function Para_Requester_Send( request ) {

    // Do not accept request without postback strings
    if(request.postback == null) {
        alert ("Always remember postback");
        return;
    }
    // cache avoidance 
    request.timestamp = new Date().getMilliseconds();

    this.pending_requests.push( request );
    this.send_next( );
}


function Para_Requester_SendNext() {
    if(this.current_request != null)
        return;

    if(this.pending_requests.length == 0)
        return;

    var req = this.pending_requests.shift();
    this.current_request = req;

    var requester = new Request.JSON2( { url: this.url,
                                        method: 'post',
                                        onComplete: Para_Requester_Response,
                                        onFailure:  Para_Requester_Error,
                                        onRequest:  Para_Requester_Request
        }
        );

    requester.send( req );
}


// this handlers are called outside of the object scope, so they have to access the object
// from outside, which really sucks.
function Para_Requester_Response( o ) {
    var postback  = o.postback;
    var requester = parapara.requester;

    if(postback == null) {
        alert("Para_Requester_Response failure 01 " + o.error_id + ":" + o.description );
        return;
    }

    if(requester.current_request == null) {
        alert("Para_Requester_Response failure 02");
        return;
    }

    if(postback != requester.current_request.postback) {
        alert("Para_Requester_Response failure 03");
        return;
    }

    requester.current_request = null;
    requester.send_next();

    parapara.rpc_response( o );
}


function Para_Requester_Error( e ) {
     alert("some RPC error" + e);
}

function Para_Requester_Request() {

}
